package panel.sinaWeiCo
{
	import com.sina.microblog.MicroBlog;
	import com.sina.microblog.events.MicroBlogErrorEvent;
	
	import flash.desktop.NativeApplication;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.LocationChangeEvent;
	import flash.geom.Rectangle;
	import flash.media.StageWebView;
	import flash.text.TextField;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	import main.LocalStoreInfo;

	/**
	 * 新浪微博测试
	 * @author shaorui
	 */	
	public class SinaWeibo extends Sprite
	{
		/**你的APP ID*/
		private static var appKey:String = "1299377837";
		/**你的APP秘钥*/
		private static var appSecret:String = "5bd5b9cfda62e1e3a3ce2cecef544697";
		/**新浪微博接口封装*/
		private var mb:MicroBlog;
		/**令牌*/
		private var accessToken:String;
		/**@private*/
		private var message:String = "";
		/**@private*/
		private var _message:String;
		private var _bitmapData:ByteArray;
		private var _callBack:Function;
        private var _stage:Stage;
		private var _webView:StageWebView;
		private var _localStore:LocalStoreInfo = new LocalStoreInfo();
		private var _authorCallBack:Function;
		/**@private*/
		public function SinaWeibo(value:Stage)
		{
			super();
			_stage = value;
		}
		
		public function sendWeibo(value:String,callBac:Function = null,byteArrat:ByteArray = null):void
		{
			_callBack = callBac;
			_bitmapData = byteArrat;
			_message = value;
			initUI();
		}
		
		protected function onKeyDownHandler(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.BACK)
			{
				event.preventDefault();
				event.stopPropagation();
				if(_webView)
				{
				_webView.stage = null;
				}
			}
		}
		/**@private*/
		protected function initUI():void
		{
			message = _message;
			executeMessage();
		}
		/**执行提示用户后，且用户确定的操作*/
		public function executeMessage(value:Function = null):void
		{
			//初始化对象
			_authorCallBack = value;
			_stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDownHandler);
			if(mb == null)
			{
				mb = new MicroBlog();
				mb.consumerKey = appKey;
				mb.consumerSecret = appSecret;
			}
				var localInfo:Object = _localStore.readInfo("sinaWeibo");
			if(localInfo || accessToken != null)
			{
				mb.access_token = localInfo.access_token;
//				mb.access_token = accessToken;
				sendNewWeibo();
			}
			else
			{
				//用WebView登录
				var url:String = "https://api.weibo.com/oauth2/authorize";
				url+="?client_id=" + appKey;
				url += "&response_type=token";
//				url += "&redirect_uri=http://www.tech-mx.com";
				url += "&redirect_uri=http://www.baidu.com";
				url += "&display=mobile";
				if(!_webView)
				{
				_webView = new StageWebView();
				_webView.stage = _stage;
				_webView.viewPort = new Rectangle(0,0,_stage.stageWidth,_stage.stageHeight);
				_webView.loadURL(url);
				_webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE,htmlPageLocationChangeHandler);
				}
			}
		}
		
		/**
		 * 根据URL的变化，获取授权码
		 * @param event
		 */		
		protected function htmlPageLocationChangeHandler(event:LocationChangeEvent):void
		{
			var lc:String = _webView.location;
			//logger.info(lc);
			//授权成功的情况： 
			var arr:Array = String(lc.split("#")[1]).split("&");
			var access_token:String = "";
			var expires_in:String = "";
			var remind_in:String = "";
			var uid:String = "";
			for (var i:int = 0 ; i < arr.length; i ++)
			{
				var str:String = arr[i];
				if (str.indexOf("access_token=") >= 0) access_token = str.split("=")[1];
				if (str.indexOf("expires_in=") >= 0) expires_in = str.split("=")[1];
				if (str.indexOf("remind_in=") >= 0) remind_in = str.split("=")[1];
				if (str.indexOf("uid=") >= 0) uid = str.split("=")[1];
			}
			if(access_token != "")
			{
				//说明登陆成功
				_webView.removeEventListener(Event.LOCATION_CHANGE, htmlPageLocationChangeHandler);
				_webView.stage = null;
				_webView.dispose();
				trace("剩余时间：" + expires_in);
				_localStore.storeInfo("sinaWeibo",{access_token:access_token,expires_in:expires_in,remind_in:remind_in,uid:uid,applyTime:getTimer()});
				accessToken = access_token;
				mb.access_token = accessToken;
				sendNewWeibo();
			}
			//如果用户取消
			var index:int = lc.search(/error_code=[\d]{5}/g);
			if(index != -1)
			{
				_webView.removeEventListener(Event.LOCATION_CHANGE, htmlPageLocationChangeHandler);
				trace("\n"+"因为您取消了授权，所以无法完成微博操作");
				//remove webpage
				_webView.stage = null;
				_webView.dispose();
			}
		}
		/**发送一条新微博*/
		private function sendNewWeibo():void
		{
			if(_authorCallBack != null)
			{
				_authorCallBack();
				return;
			}
			mb.addEventListener("callWeiboApiResult",callWeiboApiResultHandler);
			mb.addEventListener("callWeiboApiError",callWeiboApiResultHandler);
			if(_bitmapData != null)
			{
				mb.callWeiboAPI("2/statuses/upload",{status:message,pic:_bitmapData},"POST","callWeiboApiResult","callWeiboApiError");
			}else
			{
			mb.callWeiboAPI("2/statuses/update",{status:message},"POST","callWeiboApiResult","callWeiboApiError");
			}
		}
		/**调用API的结果*/
		private function callWeiboApiResultHandler(event:Event):void
		{
			if(event.type == "callWeiboApiResult")
			{
				_callBack();
				_stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDownHandler);
				trace("\n"+"微博已经发布成功!");
			}
			else
			{
				trace("\n"+"调用失败:"+(event as MicroBlogErrorEvent).message);
			}
		}
	}
}